import PySimpleGUI as sg
import cert
from const import * 
import os
import util
from excel import excelObj

sg.theme('Green')

# All the stuff inside your window.
layout_set= [
    [
        sg.Text('要操作的Excel文件:', size=(15,1)),sg.Input(key='_excel_file_'), sg.FileBrowse(button_text='浏览',file_types=supported_excel_filetype)
    ],
    [
        sg.Text('要操作的Sheet名:', size=(15,1)),sg.InputText(key='_sheet_',default_text='Sheet1', size=(10,1))
        # sg.Text('姓名所在列为:', size=(10,1)),sg.InputText(key='_sheet_name_',default_text='A', size=(2,1)),
        # sg.Text('身份证号码所在列为:', size=(15,1)),sg.InputText(key='_sheet_id_',default_text='B', size=(2,1))
    ],
    [
        sg.Text('根目录:'),sg.Text(key='_home_',size=(50,1))
    ],
    [
        sg.Button('确定',key='_set_ok_'),sg.Text('',key='_show_sheet_',size=(50,1))
    ]
            ]

layout_insert= [
    [
         sg.Text('姓名:',size=(5, 1)), sg.InputText(size=(10,1),key='_insert_name_',enable_events=True),
         sg.Text('身份证号码:',size=(10, 1)), sg.InputText(size=(20,1),key='_insert_pid_',enable_events=True)
    ],
    [
        sg.Button('录入',key='_insert_start_'), sg.Text('成功录入到文件!',size=(50,1),key='_insert_tip_',visible=False)
    ]
            ]

layout_query = [ 
    [
        sg.Text('姓名:',size=(5, 1)), sg.InputText(size=(10,1),key='q_name'),
        sg.Text('性别:',size=(5, 1)), sg.Combo(values=q_gender,default_value=q_gender[0], size=(5, 1),key='q_gender')
    ],
    [
        sg.CalendarButton('出生日期起:',size=(13, 1),target=('q_birth_start'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(12, 1),key='q_birth_start'),
        sg.CalendarButton('出生日期止:',size=(13, 1),target=('q_birth_end'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(12, 1),key='q_birth_end')
    ],
    [
        sg.Text('学历:',size=(5, 1)), sg.Combo(values=q_education,default_value=q_education[0], size=(5, 1),key='q_education'),
        sg.Text('学位:',size=(5, 1)),sg.Combo(values=q_degree,default_value=q_degree[0], size=(5, 1),key='q_degree'),
        sg.Text('职称:',size=(5, 1)), sg.InputText(size=(20, 1),key='q_title'),
        sg.Text('研究方向:',size=(8, 1)), sg.InputText(size=(20, 1),key='q_research')
    ],
    [
        sg.CalendarButton('团队合作协议日期起:',target=('q_team_start'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(10, 1),key='q_team_start'),
        sg.CalendarButton('团队合作协议日期止:',target=('q_team_end'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(10, 1),key='q_team_end')
    ],
    [
        sg.Text('是否承担项目:',size=(10, 1)), sg.Combo(values=q_item_if,default_value=q_item_if[0], size=(5, 1),key='q_item_if')
    ],
    [
        sg.Text('项目名称:',size=(13, 1)), sg.InputText(size=(12, 1),key='q_item_name'),
        sg.Text('合同编号:',size=(13, 1)), sg.InputText(size=(12, 1),key='q_item_id')  
    ],
    [
        sg.CalendarButton('项目合同日期起:',target=('q_item_date_start'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(12, 1),key='q_item_date_start'),
        sg.CalendarButton('项目合同日期止:',target=('q_item_date_end'),format='%Y-%m-%d',button_color=('#fdcb52','#2c2825')), sg.InputText(size=(12, 1),key='q_item_date_end')
    ],
    [
         sg.Text('项目合同金额起:',size=(13, 1)), sg.InputText(size=(12,1),key='q_item_price_start'),
         sg.Text('项目合同金额止:',size=(13, 1)), sg.InputText(size=(12,1),key='q_item_price_end')
    ],
    [
        sg.Button('查询',key='_query_start_'), 
        sg.Button('重置',key='_query_reset_', disabled=True), 
        sg.InputText('',enable_events=True,key='_query_save_as_',visible=False),
        sg.FileSaveAs('导出查询结果',enable_events=True,target='_query_save_as_',
        # file_types=supported_excel_filetype,
        disabled=True,key='_query_save_as_btn_')
    ],
    [
        sg.Column([[
                sg.Table(values=[['' for row in range(len(table_headers))]for col in range(1)],
                        headings=table_headers,
                        enable_events=True,
                        auto_size_columns=True,
                        display_row_numbers=False,
                        font=font,
                        key='_query_table_',
                        # background_color='#2c2825',
                        # alternating_row_color='brown',
                        # text_color='red',
                        # visible=False,
                        select_mode=sg.TABLE_SELECT_MODE_BROWSE,
                        num_rows=10,
                        vertical_scroll_only=False,
                        hide_vertical_scroll=False
                        )
                ]],
                pad=(0,0),
                visible=False,
                key='_column_table_'
            )
    ]
        ]

layout = [
    [
        sg.TabGroup(
            [
                [
                    sg.Tab('加载Excel', layout_set,key='_set_'),
                    sg.Tab('查询系统', layout_query, key='_query_'),
                    sg.Tab('录入系统', layout_insert,key='_insert_')
                ]
                
            ],
            enable_events=True)
    ]
    ]

# Create the Window
window = sg.Window(
    '人力资源查询录入系统', 
    layout,
    font=font,
    # size=(940,293),
    # resizable=True,
    location = location_main
     ).Finalize()
w_x, w_y = window.Size

window.Element('_query_table_').StartingRowNumber=1
# window.Element('_query_table_').RowHeaderText='序号'

print('first win size:',window.Size)
print('first Column size:',window.Element('_column_table_').get_size())
col_y_size =None
# Event Loop to process "events" and get the "values" of the inputs
df_query=None
# home dir
home_dir = None
while True:
    if excelObj.excel_file:
        window.Element('_query_start_').SetTooltip(excelObj.excel_file)
        window.Element('_insert_start_').SetTooltip(excelObj.excel_file)
    event, values = window.read()
    if event in (None, 'Cancel'):	# if user closes window or clicks cancel
        break
    print('You entered ', event,values)
    
    if event == '_query_table_':
        click_row_index= values['_query_table_'][0]
        select = df_query.iloc[click_row_index:click_row_index+1,0:4].values.tolist()
        print('Select row:',select)
        try:
            folder_name = '{}{}'.format(int(select[0][0]),select[0][1])
            print(f'dirname:{folder_name}')
            pdfs, no_cet = util.loopFolder(os.path.join(home_dir,folder_name))
            print('loopdir:\n',pdfs,'\n',no_cet)
            if no_cet:
                sg.PopupAutoClose('文夹下没有子文件夹（身份证、学历证书等）',title=folder_name)
            else:
                cert.modal_window(sg,pdfs,folder_name)
        except:
            pass
    if event == '_set_ok_' and values['_excel_file_'] !='':
        excelObj.excel_file = values['_excel_file_']
        
        # excelObj.col_name = values['_sheet_name_']
        # excelObj.col_id = values['_sheet_id_']
        excelObj.wb = None

        window.Element('_show_sheet_').update('可用sheet为：'+','.join(excelObj.ListSheet()))

        home_dir = os.path.dirname(excelObj.excel_file)
        window.Element('_home_').update(home_dir)

    if event == '_insert_start_' :
        if excelObj.excel_file is None:
            sg.PopupError('请事设置【系统配置】',location=location_popup)
            continue
        if values['_insert_name_'] == '' or values['_insert_pid_'] == '':
            sg.PopupError('没有身份证号码或者姓名!',location=location_popup)
            continue
        else:
            window.Element('_insert_tip_').update(visible=True)

        try:
            seq_id = excelObj.insert(values['_insert_name_'],values['_insert_pid_'])
            util.createDir(home_dir,'{}{}'.format(seq_id,values['_insert_name_']))
        except PermissionError:
            sg.PopupError('请先关闭Excel文件再插入!',location=location_popup)
            continue
        

        
    if event in [ '_insert_name_','_insert_pid_'] :
        window.Element('_insert_tip_').update(visible=False)
    
    if event == '_query_start_':
        if excelObj.excel_file is None:
            sg.PopupError('请事设置【系统配置】',location=location_popup)
            continue

        window.Element('_column_table_').update(visible=True)
        window.Element('_query_reset_').update(disabled=False)
        window.Element('_query_save_as_btn_').update(disabled=False)
        window.Refresh()
        window.Refresh()
        
        if not col_y_size:
            _col_size = window.Element('_column_table_').get_size()
            _, col_y_size = _col_size
            print('display Column size:',_col_size)
            print('display win size:',window.Size)

        window.Size =  w_x, w_y+col_y_size
        df_query = excelObj.query(util.createQueryCondition(values))
        window.Element('_query_table_').update(util.format_table_data(df_query[table_headers].values.tolist()))

    if event == '_query_reset_':
        window.Element('_column_table_').update(visible=False)
        window.Element('_query_table_').update([['' for row in range(len(table_headers))]for col in range(1)])
        window.Size = w_x,w_y
    if event == '_query_save_as_':
        export_excel=values['_query_save_as_']
        if export_excel == '':
            continue
        if str(export_excel).find('.') == -1:
            export_excel += '.xlsx'
        df_query.to_excel(export_excel,index=False)
    window.Refresh()
    window.Refresh()
    print('win size:',window.Size)
    

window.close()